import xml.etree.ElementTree as ET


def xml_to_dict(xml_path):
    """
    将xml文件转换为dict
    """
    xml_dict = dict()
    xml_tree = ET.parse(xml_path)
    xml_root = xml_tree.getroot()
    xml_dict[xml_root.tag] = parse_xml_to_dict(xml_root)
    return xml_dict


def parse_xml_to_dict(xml_root):
    # 该tag没有属性，也没有子tag则返回值<EXECUTIONNODES>single</EXECUTIONNODES>
    if len(xml_root.attrib) == 0 and len(xml_root) == 0:
        return xml_root.text
    ret_dict = dict()
    attrib = {"@" + str(key): value for key, value in xml_root.attrib.items()}
    ret_dict.update(attrib)
    # 当tag包裹的值不为空时，要设置#text
    if xml_root.text is not None and xml_root.text.strip() != '':
        ret_dict['#text'] = xml_root.text
    for child in xml_root:
        if child.tag not in ret_dict.keys():
            ret_dict[child.tag] = parse_xml_to_dict(child)
        else:
            # xml有多个tag相同时，该tag则改为列表存储
            if not isinstance(ret_dict[child.tag], list):
                child_list = [ret_dict[child.tag]]
                ret_dict[child.tag] = child_list
            ret_dict[child.tag].append(parse_xml_to_dict(child))
    return ret_dict
